﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="FormSummarySearch.cs" company="">
//   
// </copyright>
// <summary>
//   The form summary search.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace NetworkSupervisor
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Windows.Forms;

    using AxSHDocVw;

    using DevExpress.Xpo;
    using DevExpress.XtraEditors;
    using DevExpress.XtraEditors.Controls;
    using DevExpress.XtraGrid.Views.Grid;

    using mshtml;

    using NetworkSupervisor.Helper;
    using NetworkSupervisor.Model.NetworkSupervisor;

    /// <summary>The form summary search.</summary>
    public partial class FormSummarySearch : DevExpress.XtraEditors.XtraForm
    {
        #region Fields

        /// <summary>
        /// 搜索关键字
        /// </summary>
        private string keyword;

        /// <summary>
        /// 新增信息条数
        /// </summary>
        private int newInfoCount;

        /// <summary>
        /// 搜索页面深度
        /// </summary>
        private int pages;

        /// <summary>
        /// 进度条当前位置
        /// </summary>
        private int progressCurrentPosition;

        /// <summary>
        /// 搜索类别
        /// </summary>
        private string type;

        #endregion

        #region Constructors and Destructors

        /// <summary>Initializes a new instance of the <see cref="FormSummarySearch"/> class.</summary>
        public FormSummarySearch()
        {
            this.InitializeComponent();
        }

        #endregion

        #region Methods

        /// <summary>The form key word search_ load.</summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The e.</param>
        private void FormKeyWordSearch_Load(object sender, EventArgs e)
        {
            Control.CheckForIllegalCrossThreadCalls = false;

            this.InitTypeList();
            this.InitKeywordList();

            this.axWebBrowser1.Silent = true;

            this.gridView1.ActiveFilterString = "重要程度<>'无关信息'";
        }

        /// <summary>The form key word search_ shown.</summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The e.</param>
        private void FormKeyWordSearch_Shown(object sender, EventArgs e)
        {
            this.cbKeyword.SelectedIndex = 0;
            this.cbType.SelectedIndex = 0;
        }

        /// <summary>
        /// 初始化关键字列表
        /// </summary>
        private void InitKeywordList()
        {
            XPCollection<ta关键字> collection = new XPCollection<ta关键字>(this.session1);
            foreach (ta关键字 item in collection)
            {
                this.cbKeyword.Properties.Items.Add(item.关键字);
            }
        }

        /// <summary>The init type list.</summary>
        private void InitTypeList()
        {
            XPCollection<ta类别> collection = new XPCollection<ta类别>(this.session1);
            foreach (ta类别 item in collection)
            {
                this.cbType.Properties.Items.Add(item.类别);
            }
        }

        /// <summary>The refresh grid view.</summary>
        private void RefreshGridView()
        {
            this.keyword = this.cbKeyword.Text;
            this.type = this.cbType.Text;
            if (this.type == "关注" || this.type == "敏感")
            {
                this.cbKeyword.Properties.Items.Clear();
                IEnumerable<ta网址> itemGZs = new XPCollection<ta网址>(this.session1).Where(o => o.类别 == this.type);
                foreach (ta网址 itemGZ in itemGZs)
                {
                    this.cbKeyword.Properties.Items.Add(itemGZ.网址);
                }
            }
            else
            {
                this.cbKeyword.Properties.Items.Clear();
                XPCollection<ta关键字> itemGZs = new XPCollection<ta关键字>(this.session1);
                foreach (ta关键字 itemGZ in itemGZs)
                {
                    this.cbKeyword.Properties.Items.Add(itemGZ.关键字);
                }
            }

            this.XPC搜索结果.CriteriaString = string.Format("关键字='{0}' AND 类别='{1}'", this.keyword, this.type);
        }

        /// <summary>The update database and grid view.</summary>
        /// <param name="articleList">The article list.</param>
        private void UpdateDatabaseAndGridView(IList<ArticleInfo> articleList)
        {
            foreach (ArticleInfo articleInfo in articleList)
            {
                IEnumerable<ta搜索结果> cast = this.XPC搜索结果.Cast<ta搜索结果>();
                bool has = cast.Any(o => o.标题 == articleInfo.Title && o.类别 == this.type);
                if (!has)
                {
                    ta搜索结果 item = new ta搜索结果(this.session1);
                    item.标题 = articleInfo.Title;
                    item.链接 = articleInfo.Href;
                    item.收录时间 = articleInfo.Datetime;
                    item.信息摘要 = articleInfo.Content;
                    item.关键字 = articleInfo.Keyword;
                    item.类别 = articleInfo.Type;
                    item.信息来源 = articleInfo.From;
                    item.处理情况 = "待处理";
                    item.Save();
                    this.UIThread(() => this.XPC搜索结果.Add(item));
                    this.UIThread(() => this.gridView1.FocusedRowHandle = this.gridView1.RowCount - 1);
                    this.newInfoCount++;
                    System.Threading.Thread.Sleep(50);
                }
            }
        }

        /// <summary>
        /// 更新关键字
        /// </summary>
        private void UpdateKeyword()
        {
            if (new XPCollection<ta关键字>(this.session1).All(o => o.关键字 != this.keyword))
            {
                ta关键字 itemKey = new ta关键字(this.session1);
                itemKey.关键字 = this.keyword;
                itemKey.Save();
                this.cbKeyword.Properties.Items.Add(this.keyword);
            }
        }

        /// <summary>The ax web browser 1_ document complete.</summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The e.</param>
        private void axWebBrowser1_DocumentComplete(object sender, DWebBrowserEvents2_DocumentCompleteEvent e)
        {
        }

        /// <summary>The ax web browser 1_ navigate complete 2.</summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The e.</param>
        private void axWebBrowser1_NavigateComplete2(object sender, DWebBrowserEvents2_NavigateComplete2Event e)
        {
            IHTMLDocument2 doc = (sender as AxSHDocVw.AxWebBrowser).Document as mshtml.IHTMLDocument2;
            doc.parentWindow.execScript("window.alert=null", "javascript");
            doc.parentWindow.execScript("window.confirm=null", "javascript");
            doc.parentWindow.execScript("window.open=null", "javascript");
            doc.parentWindow.execScript("window.showModalDialog=null", "javascript");
            doc.parentWindow.execScript("window.close=null", "javascript");
        }

        /// <summary>The ax web browser 1_ new window 2.</summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The e.</param>
        private void axWebBrowser1_NewWindow2(object sender, DWebBrowserEvents2_NewWindow2Event e)
        {
            e.cancel = true;
        }

        /// <summary>The ax web browser 1_ new window 3.</summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The e.</param>
        private void axWebBrowser1_NewWindow3(object sender, DWebBrowserEvents2_NewWindow3Event e)
        {
            e.cancel = true;
        }

        /// <summary>The btn search_ click.</summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The e.</param>
        private void btnSearch_Click(object sender, EventArgs e)
        {
            this.keyword = this.cbKeyword.Text;
            this.type = this.cbType.Text;

            if (this.type == "关注")
            {
                XtraMessageBox.Show("关注类别数据由关注信息监控自动获取，无需在此处搜索");
                return;
            }

            if (this.type == "敏感")
            {
                XtraMessageBox.Show("敏感类别数据由敏感信息监控自动获取，无需在此处搜索");
                return;
            }

            this.UpdateKeyword();

            this.XPC搜索结果.CriteriaString = string.Format("关键字='{0}' AND 类别='{1}'", this.keyword, this.type);

            this.pages = 10;
            this.progressBarControl1.Properties.Maximum = this.pages;
            this.progressCurrentPosition = 0;
            this.newInfoCount = 0;

            System.Threading.ThreadPool.QueueUserWorkItem(this.callBack);
        }

        /// <summary>The call back.</summary>
        /// <param name="state">The state.</param>
        private void callBack(object state)
        {
            this.UIThread(() => btnSearch.Enabled = false);
            bool IsSearched = false;
            switch (this.type)
            {
                case "综合":
                    this.progressBarControl1.Position = 0;
                    this.progressBarControl1.Properties.Maximum = this.pages;
                    this.progressCurrentPosition = 0;
                    for (int page = 0; page < this.pages; page++)
                    {
                        IList<ArticleInfo> articleList = SearchHelper.GetAllArticleList(this.keyword, page, this.type);
                        this.UpdateDatabaseAndGridView(articleList);
                        this.progressCurrentPosition++;
                        this.UIThread(() => this.progressBarControl1.Position = this.progressCurrentPosition);
                    }

                    IsSearched = true;
                    break;
                case "新闻":
                case "博客":
                case "论坛":
                    {
                        IEnumerable<ta网址> items = new XPCollection<ta网址>(this.session1).Where(o => o.类别 == this.type);
                        this.progressBarControl1.Position = 0;
                        this.progressBarControl1.Properties.Maximum = items.Count();
                        this.progressCurrentPosition = 0;
                        foreach (ta网址 item in items)
                        {
                            IList<ArticleInfo> articleList = SearchHelper.GetAllArticleList(this.keyword, 0, this.type, item.网址);
                            this.UpdateDatabaseAndGridView(articleList);
                            this.progressCurrentPosition++;
                            this.UIThread(() => this.progressBarControl1.Position = this.progressCurrentPosition);
                        }
                    }

                    IsSearched = true;

                    break;
                case "微博":
                    {
                        IEnumerable<ta网址> items = new XPCollection<ta网址>(this.session1).Where(o => o.类别 == this.type);
                        this.progressBarControl1.Position = 0;
                        this.progressBarControl1.Properties.Maximum = items.Count();
                        this.progressCurrentPosition = 0;
                        foreach (ta网址 item in items)
                        {
                            this.progressCurrentPosition++;
                            string url = item.网址.Replace("keyword", this.keyword);
                            this.UIThreadBeginInvoke(
                                () =>
                                    {
                                        try
                                        {
                                            System.Diagnostics.Process.Start(url);
                                        }
                                        catch (Exception ex1)
                                        {
                                            try
                                            {
                                                System.Diagnostics.Process.Start(@"C:\Program Files\Internet Explorer\iexplore.exe", url);
                                            }
                                            catch (Exception ex2)
                                            {
                                            }
                                        }
                                    });
                        }

                        IList<ArticleInfo> articleList = SearchHelper.GetWeiBoArticleList(this.keyword, this.type);
                        this.UpdateDatabaseAndGridView(articleList);
                        this.UIThread(() => this.progressBarControl1.Position = this.progressCurrentPosition);
                    }

                    IsSearched = false;
                    break;
                case "关注":
                    this.UIThread(() => XtraMessageBox.Show("关注类别数据由关注信息监控自动获取，无需在此处搜索"));
                    IsSearched = false;
                    break;
                case "敏感":
                    this.UIThread(() => XtraMessageBox.Show("敏感类别数据由敏感信息监控自动获取，无需在此处搜索"));
                    IsSearched = false;
                    break;
                default:
                    this.UIThread(() => XtraMessageBox.Show("类别出错，选择的类别为：" + this.type));
                    IsSearched = false;
                    break;
            }

            this.UIThread(() => btnSearch.Enabled = true);
            if (IsSearched)
            {
                this.UIThread(() => XtraMessageBox.Show(string.Format("搜索完成，共新增{0}条", this.newInfoCount)));
            }
        }

        /// <summary>The cb type_ selected index changed.</summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The e.</param>
        private void cbType_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.RefreshGridView();
            if (this.type == "关注" || this.type == "敏感")
            {
                this.cbKeyword.SelectedIndex = 0;
            }
        }

        /// <summary>The grid view 1_ custom draw row indicator.</summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The e.</param>
        private void gridView1_CustomDrawRowIndicator(object sender, RowIndicatorCustomDrawEventArgs e)
        {
            if (e.Info.IsRowIndicator)
            {
                e.Info.DisplayText = e.RowHandle.ToString();
            }
        }

        /// <summary>The grid view 1_ double click.</summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The e.</param>
        private void gridView1_DoubleClick(object sender, EventArgs e)
        {
            if (this.gridView1.RowCount < 1)
            {
                return;
            }

            ta搜索结果 item = this.gridView1.GetFocusedRow() as ta搜索结果;
            string url = item.链接;
            this.groupControl3.Text = item.标题;

            System.Threading.ThreadPool.QueueUserWorkItem(this.refreshWeb, url);
        }

        /// <summary>The refresh web.</summary>
        /// <param name="state">The state.</param>
        private void refreshWeb(object state)
        {
            this.UIThread(() => this.axWebBrowser1.Navigate(Convert.ToString(state)));
        }

        /// <summary>处理情况</summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton10_Click(object sender, EventArgs e)
        {
            SimpleButton button = sender as SimpleButton;
            if (this.gridView1.SelectedRowsCount > 1)
            {
                int[] handels = this.gridView1.GetSelectedRows();
                foreach (int handel in handels)
                {
                    ta搜索结果 item = this.gridView1.GetRow(handel) as ta搜索结果;
                    item.处理情况 = button.Text;
                    item.标记时间 = DateTime.Now;
                    item.Save();
                }
            }
            else
            {
                this.标记时间DateEdit.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                this.处理情况TextEdit.Text = button.Text;
            }

            this.处理情况TextEdit.Focus();
            this.gridView1.Focus();
            button.Focus();
        }

        /// <summary>The simple button 12_ click.</summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The e.</param>
        private void simpleButton12_Click(object sender, EventArgs e)
        {
            SaveFileDialog f = new SaveFileDialog();
            f.Filter = "Excel(*.xls)|*.xls";
            f.FileName = "处理情况列表" + DateTime.Now.ToString("yyyy年MM月dd日") + ".xls";
            if (f.ShowDialog() == DialogResult.OK)
            {
                this.gridControl1.ExportToXls(f.FileName);
                if (XtraMessageBox.Show("导出成功，是否打开？", string.Empty, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
                {
                    System.Diagnostics.Process.Start(f.FileName);
                }
            }
        }

        /// <summary>The simple button 13_ click.</summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The e.</param>
        private void simpleButton13_Click(object sender, EventArgs e)
        {
            string url = this.链接TextEdit.Text;
            if (url != string.Empty)
            {
                System.Diagnostics.Process.Start(url);
            }
        }

        /// <summary>SJ情况登记</summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton1_Click(object sender, EventArgs e)
        {
            SimpleButton button = sender as SimpleButton;
            this.标记时间DateEdit.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

            string text = button.Text;
            if (text == "无")
            {
                text = string.Empty;
            }

            this.SJ情况TextEdit.Text = text;
            this.SJ情况TextEdit.Focus();
            this.gridView1.Focus();
            button.Focus();
        }

        /// <summary>正负面情况</summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton6_Click(object sender, EventArgs e)
        {
            SimpleButton button = sender as SimpleButton;

            this.标记时间DateEdit.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

            this.正负面情况TextEdit.Text = button.Text;
            this.正负面情况TextEdit.Focus();
            this.gridView1.Focus();
            button.Focus();
        }

        /// <summary>重要程度</summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton7_Click(object sender, EventArgs e)
        {
            SimpleButton button = sender as SimpleButton;
            if (button.Text == "无关信息")
            {
                if (XtraMessageBox.Show("是否确认将选择信息标识为无关信息，标识后将不再显示，是否确认？", string.Empty, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) != DialogResult.OK)
                {
                    return;
                }
            }

            if (this.gridView1.SelectedRowsCount > 1)
            {
                int[] handels = this.gridView1.GetSelectedRows();
                foreach (int handel in handels)
                {
                    ta搜索结果 item = this.gridView1.GetRow(handel) as ta搜索结果;
                    item.重要程度 = button.Text;
                    item.标记时间 = DateTime.Now;
                    item.Save();
                }
            }
            else
            {
                this.标记时间DateEdit.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

                this.重要程度TextEdit.Text = button.Text;
            }

            this.重要程度TextEdit.Focus();
            this.gridView1.Focus();
            button.Focus();
        }

        /// <summary>The txt keyword_ properties_ button click.</summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The e.</param>
        private void txtKeyword_Properties_ButtonClick(object sender, ButtonPressedEventArgs e)
        {
            switch (e.Button.Kind)
            {
                case ButtonPredefines.Delete:
                    if (this.type == "关注")
                    {
                        XtraMessageBox.Show("无法在此处删除关注关键字，请在系统设置里面清除");
                        return;
                    }

                    if (this.type == "敏感")
                    {
                        XtraMessageBox.Show("无法在此处删除敏感关键字，请在系统设置里面清除");
                        return;
                    }

                    DialogResult result = XtraMessageBox.Show("是否确认删除关键字，删除关键字将同时删除历史搜索和处理信息。", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
                    if (result == DialogResult.OK)
                    {
                        string key = this.cbKeyword.Text;
                        this.cbKeyword.Properties.Items.Remove(key);
                        string sql = string.Format("DELETE FROM ta关键字 WHERE 关键字='{0}'", key);
                        this.session1.ExecuteNonQuery(sql);

                        // 不删除"关注","敏感"历史记录
                        sql = string.Format("DELETE FROM ta搜索结果 WHERE 关键字='{0}' AND 类别 NOT IN('关注','敏感')", key);
                        this.session1.ExecuteNonQuery(sql);
                        this.cbKeyword.Text = string.Empty;
                        this.cbKeyword.SelectedIndex = 0;
                        this.txtKeyword_SelectedIndexChanged(null, null);
                    }

                    break;
            }
        }

        /// <summary>The txt keyword_ selected index changed.</summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The e.</param>
        private void txtKeyword_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.RefreshGridView();
        }

        /// <summary>The 链接 text edit_ double click.</summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The e.</param>
        private void 链接TextEdit_DoubleClick(object sender, EventArgs e)
        {
            string url = this.链接TextEdit.Text;
            if (url != string.Empty)
            {
                System.Diagnostics.Process.Start(url);
            }
        }

        #endregion
    }
}